<template>
  <view class="area-container">
    <!-- 服务说明区域 -->
    <view class="intro-section">
      <view class="intro-content">
        <u-icon name="home" color="#409eff" size="24"></u-icon>
        <text class="intro-text">请详细填写保洁区域信息，我们会为您安排相应的保洁工作</text>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-container">
      <u-form :model="formData" ref="formRef" :rules="rules">
        <!-- 区域信息 -->
        <view class="form-section">
          <view class="section-title">
            <text class="title-icon">◎◎</text>
            <text class="title-text">区域信息 *</text>
          </view>
          
          <!-- 所属社区 -->
          <view class="form-item">
            <view class="form-label">所属社区 *</view>
            <view class="select-wrapper" @click="showCommunityActionSheet">
              <text class="select-text">{{ getCommunityText(formData.communityId) || '请选择社区' }}</text>
              <u-icon name="arrow-right" size="16" color="#999"></u-icon>
            </view>
          </view>

          <!-- 区域名称 -->
          <view class="form-item">
            <view class="form-label">区域名称 *</view>
            <u-input 
              v-model="formData.areaName" 
              placeholder="请输入区域名称"
              maxlength="50"
              class="form-input"
            />
          </view>

          <!-- 区域类型 -->
          <view class="form-item">
            <view class="form-label">区域类型 *</view>
            <view class="select-wrapper" @click="showAreaTypeActionSheet">
              <text class="select-text">{{ getAreaTypeText(formData.areaType) || '请选择区域类型' }}</text>
              <u-icon name="arrow-right" size="16" color="#999"></u-icon>
            </view>
          </view>

          <!-- 位置描述 -->
          <view class="form-item">
            <view class="form-label">位置描述</view>
            <u-textarea 
              v-model="formData.location" 
              placeholder="请输入位置描述"
              maxlength="200"
              :auto-height="true"
              class="form-textarea"
            />
          </view>
        </view>

        <!-- 保洁配置 -->
        <view class="form-section">
          <view class="section-title">
            <text class="title-icon">△△</text>
            <text class="title-text">保洁配置</text>
          </view>

          <!-- 保洁标准 -->
          <view class="form-item">
            <view class="form-label">保洁标准</view>
            <u-textarea 
              v-model="formData.cleaningStandard" 
              placeholder="请输入保洁标准"
              maxlength="500"
              :auto-height="true"
              class="form-textarea"
            />
          </view>

          <!-- 保洁频次 -->
          <view class="form-item">
            <view class="form-label">保洁频次 *</view>
            <view class="select-wrapper" @click="showFrequencyActionSheet">
              <text class="select-text">{{ getFrequencyText(formData.frequency) || '请选择保洁频次' }}</text>
              <u-icon name="arrow-right" size="16" color="#999"></u-icon>
            </view>
          </view>

          <!-- 负责人 -->
          <view class="form-item">
            <view class="form-label">负责人</view>
            <view class="select-wrapper" @click="showUserActionSheet">
              <text class="select-text">{{ getUserText(formData.responsibleUserId) || '请选择负责人' }}</text>
              <u-icon name="arrow-right" size="16" color="#999"></u-icon>
            </view>
          </view>

          <!-- 状态 -->
          <view class="form-item">
            <view class="form-label">状态 *</view>
            <view class="status-options">
              <view 
                class="status-option" 
                :class="{ active: formData.status === 1 }"
                @click="selectStatus(1)"
              >
                <view class="status-icon">✓</view>
                <text class="status-text">启用</text>
              </view>
              <view 
                class="status-option" 
                :class="{ active: formData.status === 0 }"
                @click="selectStatus(0)"
              >
                <view class="status-icon">✗</view>
                <text class="status-text">停用</text>
              </view>
            </view>
          </view>
        </view>
      </u-form>
    </view>

    <!-- 提交按钮区域 -->
    <view class="submit-section">
      <u-button 
        type="default" 
        @click="goBack"
        class="btn-cancel"
      >
        取消
      </u-button>
      <u-button 
        type="primary" 
        @click="submitForm"
        :loading="submitting"
        class="btn-submit"
      >
        {{ submitting ? '保存中...' : '保存' }}
      </u-button>
    </view>
  </view>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { createCleaningArea } from '@/api/cleaning'
import { staffApi } from '@/api/staff'
import { commonApi } from '@/api/property'

export default {
  name: 'AreaAdd',
  
  setup() {
    const formRef = ref(null)
    const submitting = ref(false)
    
    // 表单数据
    const formData = reactive({
      communityId: null,
      areaName: '',
      areaType: '大厅',
      location: '',
      cleaningStandard: '',
      frequency: '每日',
      responsibleUserId: null,
      status: 1
    })
    
    // 表单验证规则
    const rules = {
      communityId: [
        { required: true, message: '请选择所属社区', trigger: 'change' }
      ],
      areaName: [
        { required: true, message: '请输入区域名称', trigger: 'blur' },
        { min: 2, max: 50, message: '区域名称长度为2-50个字符', trigger: 'blur' }
      ],
      areaType: [
        { required: true, message: '请选择区域类型', trigger: 'change' }
      ],
      frequency: [
        { required: true, message: '请选择保洁频次', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    // 选项数据
    const communityOptions = ref([])
    const areaTypeOptions = ref([
      { label: '大厅', value: '大厅' },
      { label: '走廊', value: '走廊' },
      { label: '楼梯', value: '楼梯' },
      { label: '电梯', value: '电梯' },
      { label: '公共区域', value: '公共区域' },
      { label: '绿化带', value: '绿化带' }
    ])
    const frequencyOptions = ref([
      { label: '每日', value: '每日' },
      { label: '每周', value: '每周' },
      { label: '每月', value: '每月' }
    ])
    const userOptions = ref([])
    
    // 获取社区文本
    const getCommunityText = (value) => {
      const option = communityOptions.value.find(item => item.value === value)
      return option ? option.label : ''
    }
    
    // 获取区域类型文本
    const getAreaTypeText = (value) => {
      const option = areaTypeOptions.value.find(item => item.value === value)
      return option ? option.label : ''
    }
    
    // 获取保洁频率文本
    const getFrequencyText = (value) => {
      const option = frequencyOptions.value.find(item => item.value === value)
      return option ? option.label : ''
    }
    
    // 获取负责人文本
    const getUserText = (value) => {
      const option = userOptions.value.find(item => item.value === value)
      return option ? option.label : ''
    }
    
    // 显示社区选择ActionSheet
    const showCommunityActionSheet = () => {
      if (communityOptions.value.length === 0) {
        uni.showToast({
          title: '社区列表加载中...',
          icon: 'none'
        })
        return
      }
      
      const itemList = communityOptions.value.map(item => item.label)
      uni.showActionSheet({
        itemList: itemList,
        success: (res) => {
          const selectedOption = communityOptions.value[res.tapIndex]
          formData.communityId = selectedOption.value
        }
      })
    }
    
    // 显示区域类型选择ActionSheet
    const showAreaTypeActionSheet = () => {
      const itemList = areaTypeOptions.value.map(item => item.label)
      uni.showActionSheet({
        itemList: itemList,
        success: (res) => {
          const selectedOption = areaTypeOptions.value[res.tapIndex]
          formData.areaType = selectedOption.value
        }
      })
    }
    
    // 显示保洁频率选择ActionSheet
    const showFrequencyActionSheet = () => {
      const itemList = frequencyOptions.value.map(item => item.label)
      uni.showActionSheet({
        itemList: itemList,
        success: (res) => {
          const selectedOption = frequencyOptions.value[res.tapIndex]
          formData.frequency = selectedOption.value
        }
      })
    }
    
    // 显示负责人选择ActionSheet
    const showUserActionSheet = () => {
      if (userOptions.value.length === 0) {
        uni.showToast({
          title: '用户列表加载中...',
          icon: 'none'
        })
        return
      }
      
      const itemList = userOptions.value.map(item => item.label)
      uni.showActionSheet({
        itemList: itemList,
        success: (res) => {
          const selectedOption = userOptions.value[res.tapIndex]
          formData.responsibleUserId = selectedOption.value
        }
      })
    }
    
    // 选择状态
    const selectStatus = (status) => {
      formData.status = status
    }
    
    // 加载社区选项
    const loadCommunityOptions = async () => {
      try {
        const response = await commonApi.getCommunityList()
        if (response && response.success && response.data) {
          let communityList = []
          if (response.data.records && Array.isArray(response.data.records)) {
            communityList = response.data.records
          } else if (Array.isArray(response.data)) {
            communityList = response.data
          }
          
          communityOptions.value = communityList.map(community => ({
            label: community.communityName || community.name,
            value: community.id
          }))
          
          // 默认选中第一个选项
          if (communityOptions.value.length > 0 && !formData.communityId) {
            formData.communityId = communityOptions.value[0].value
          }
        }
      } catch (error) {
        console.error('加载社区列表失败:', error)
        uni.showToast({
          title: '加载社区列表失败',
          icon: 'none'
        })
      }
    }
    
    // 加载用户选项
    const loadUserOptions = async () => {
      try {
        console.log('开始加载员工列表...')
        const response = await staffApi.getStaffList({ pageNum: 1, pageSize: 100 })
        console.log('员工列表API响应:', response)
        
        if (response && response.success && response.data) {
          let userList = []
          if (response.data.records && Array.isArray(response.data.records)) {
            // 分页格式：data.records
            userList = response.data.records
            console.log('检测到分页格式数据，使用data.records')
          } else if (Array.isArray(response.data)) {
            // 直接数组格式：data
            userList = response.data
            console.log('检测到直接数组格式数据，使用data')
          }
          
          console.log('员工列表数据:', userList)
          console.log('数据长度:', userList.length)
          
          userOptions.value = userList.map(user => ({
            label: user.realName || user.name || user.username,
            value: user.id
          }))
          
          console.log('转换后的用户选项:', userOptions.value)
          
          // 默认选中第一个选项
          if (userOptions.value.length > 0 && !formData.responsibleUserId) {
            formData.responsibleUserId = userOptions.value[0].value
            console.log('默认选中用户ID:', formData.responsibleUserId)
          }
        } else {
          console.log('员工列表API响应失败:', response)
          console.log('success字段:', response?.success)
          console.log('data字段:', response?.data)
        }
      } catch (error) {
        console.error('加载用户列表失败:', error)
        console.error('错误详情:', error.message)
        console.error('错误堆栈:', error.stack)
        uni.showToast({
          title: '加载用户列表失败: ' + error.message,
          icon: 'none',
          duration: 3000
        })
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      try {
        // 表单验证
        const valid = await formRef.value.validate()
        if (!valid) return
        
        submitting.value = true
        
        // 显示加载提示
        uni.showLoading({
          title: '保存中...',
          mask: true
        })
        
        // 调用创建接口
        const response = await createCleaningArea(formData)
        
        uni.hideLoading()
        
        if (response.success) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: response.message || '保存失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('保存区域失败:', error)
        uni.showToast({
          title: '保存失败: ' + (error.message || '未知错误'),
          icon: 'none'
        })
      } finally {
        submitting.value = false
      }
    }
    
    // 返回上一页
    const goBack = () => {
      uni.navigateBack()
    }
    
    onMounted(() => {
      loadCommunityOptions()
      loadUserOptions()
    })
    
    return {
      formRef,
      formData,
      rules,
      submitting,
      communityOptions,
      areaTypeOptions,
      frequencyOptions,
      userOptions,
      getCommunityText,
      getAreaTypeText,
      getFrequencyText,
      getUserText,
      showCommunityActionSheet,
      showAreaTypeActionSheet,
      showFrequencyActionSheet,
      showUserActionSheet,
      selectStatus,
      submitForm,
      goBack
    }
  }
}
</script>

<style lang="scss" scoped>
/* 页面容器 */
.area-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 服务说明区域 */
.intro-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 16px;
  margin: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  
  .intro-content {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .intro-text {
      flex: 1;
      font-size: 14px;
      color: #666;
      line-height: 1.4;
    }
  }
}

/* 表单容器 */
.form-container {
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  margin: 0;
  padding: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 表单区块 */
.form-section {
  margin-bottom: 24px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    font-size: 15px;
    font-weight: 600;
    color: #333;
    
    .title-icon {
      font-size: 16px;
      color: #409eff;
    }
    
    .title-text {
      color: #333;
    }
  }
}

/* 表单项 */
.form-item {
  margin-bottom: 16px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .form-label {
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;
    font-weight: 500;
  }
}

/* 选择器包装器 */
.select-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  transition: all 0.3s ease;
  
  &:active {
    background: #fff;
    border-color: #409eff;
  }
  
  .select-text {
    flex: 1;
    font-size: 14px;
    color: #333;
    
    &:empty::before {
      content: attr(placeholder);
      color: #999;
    }
  }
}

/* 表单输入框 */
.form-input {
  width: 100%;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  
  &:focus {
    border-color: #409eff;
    background: #fff;
  }
}

/* 表单文本域 */
.form-textarea {
  width: 100%;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  min-height: 100px;
  
  &:focus {
    border-color: #409eff;
    background: #fff;
  }
}

/* 状态选项 */
.status-options {
  display: flex;
  gap: 12px;
  
  .status-option {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    padding: 12px 8px;
    background: #f8f9fa;
    border: 2px solid transparent;
    border-radius: 8px;
    transition: all 0.3s ease;
    
    &.active {
      background: linear-gradient(135deg, #409eff, #67c23a);
      border-color: #409eff;
      color: #fff;
    }
    
    .status-icon {
      font-size: 16px;
      font-weight: bold;
    }
    
    .status-text {
      font-size: 12px;
      text-align: center;
    }
  }
}

/* 提交按钮区域 */
.submit-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 16px;
  margin: 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 12px;
  
  .btn-cancel {
    flex: 1;
    height: 48px;
    background: #f8f9fa;
    border: 1px solid #e4e7ed;
    border-radius: 24px;
    font-size: 16px;
    font-weight: 500;
    color: #666;
    
    &:active {
      transform: scale(0.98);
    }
  }
  
  .btn-submit {
    flex: 1;
    height: 48px;
    background: linear-gradient(135deg, #409eff, #67c23a);
    border: none;
    border-radius: 24px;
    font-size: 16px;
    font-weight: 600;
    color: #fff;
    
    &:active {
      transform: scale(0.98);
    }
  }
}

/* 响应式设计 */
@media screen and (max-width: 375px) {
  .intro-section,
  .form-container,
  .submit-section {
    padding: 12px;
  }
  
  .form-input,
  .form-textarea,
  .select-wrapper {
    padding: 10px;
    font-size: 13px;
  }
  
  .status-options {
    gap: 8px;
    
    .status-option {
      padding: 10px 6px;
      
      .status-text {
        font-size: 11px;
      }
    }
  }
}

@media screen and (min-width: 414px) {
  .intro-section,
  .form-container,
  .submit-section {
    padding: 20px;
  }
}
</style>